package org.argus.job.server.system.workflow.hanlder.impl;

import java.util.Optional;

import org.argus.job.common.enums.InstanceStatus;
import org.argus.job.common.enums.TimeExpressionType;
import org.argus.job.common.enums.WorkflowNodeType;
import org.argus.job.common.model.PEWorkflowDAG;
import org.argus.job.server.common.spring.SpringUtils;
import org.argus.job.server.system.dispatch.DispatchService;
import org.argus.job.server.system.domain.JobInfoEntity;
import org.argus.job.server.system.domain.WorkflowInstanceInfoEntity;
import org.argus.job.server.system.instance.InstanceService;
import org.argus.job.server.system.management.mapper.JobInfoMapper;
import org.argus.job.server.system.workflow.hanlder.TaskNodeHandler;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Echo009
 * @since 2021/12/9
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JobNodeHandler implements TaskNodeHandler {

    private final JobInfoMapper jobInfoMapper;

    @Override
    public void createTaskInstance(PEWorkflowDAG.Node node, PEWorkflowDAG dag,
        WorkflowInstanceInfoEntity wfInstanceInfo) {
        // instanceParam 传递的是工作流实例的 wfContext
        Long instanceId =
            SpringUtils
                .getBean(InstanceService.class).create(node.getJobId(), wfInstanceInfo.getAppId(), node.getNodeParams(),
                    wfInstanceInfo.getWfContext(), wfInstanceInfo.getWfInstanceId(), System.currentTimeMillis())
                .getId();
        node.setInstanceId(instanceId);
        node.setStatus(InstanceStatus.RUNNING);
        log.info("[Workflow-{}|{}] create readyNode(JOB) instance(nodeId={},jobId={},instanceId={}) successfully~",
            wfInstanceInfo.getWorkflowId(), wfInstanceInfo.getWfInstanceId(), node.getNodeId(), node.getJobId(),
            instanceId);
    }

    @Override
    public void startTaskInstance(PEWorkflowDAG.Node node) {
        JobInfoEntity jobInfo = jobInfoMapper.selectById(node.getJobId());
        if (jobInfo == null) {
            jobInfo = new JobInfoEntity();
        }
        // 洗去时间表达式类型
        jobInfo.setTimeExpressionType(TimeExpressionType.WORKFLOW);
        SpringUtils.getBean(DispatchService.class).dispatch(jobInfo, node.getInstanceId(), Optional.empty(),
            Optional.empty());
    }

    @Override
    public WorkflowNodeType matchingType() {
        return WorkflowNodeType.JOB;
    }
}
